package org.zjx.db;

import org.zjx.common.bean.Screen;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ScreenDB {
    private static boolean isTableCreated = false;  // Flag to ensure the table is only created once
    private final SQLiteHelper dbHelper;

    public ScreenDB() {
        dbHelper = SQLiteHelper.getSingleton();
        // Only create the table once when the instance is first created
        if (!isTableCreated) {
            createTable();
            isTableCreated = true;
        }
    }

    // Create table for Screen
    public void createTable() {
        String createTable = "CREATE TABLE IF NOT EXISTS screen (\n"
                + "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
                + "    name TEXT NOT NULL,\n"
                + "    city TEXT,\n"
                + "    width TEXT,\n"
                + "    height TEXT\n"
                + ");";
        dbHelper.createTable(createTable);
    }

    // Insert a Screen record
    public void insert(Screen screen) {
        String sql = "INSERT INTO screen(name, city, width, height) VALUES(?, ?, ?, ?)";
        Object[] params = {
                screen.getName(),
                screen.isCity(),
                screen.getWidth(),
                screen.getHeight()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Update a Screen record
    public void update(Screen screen) {
        String sql = "UPDATE screen SET name = ?, city = ?, width = ?, height = ? WHERE id = ?";
        Object[] params = {
                screen.getName(),
                screen.isCity(),
                screen.getWidth(),
                screen.getHeight(),
                screen.getId()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Delete a Screen record by ID
    public void deleteById(int id) {
        String sql = "DELETE FROM screen WHERE id = ?";
        Object[] params = {id};
        dbHelper.executeUpdate(sql, params);
    }

    // Find Screen by ID
    public Screen findById(int id) {
        String sql = "SELECT * FROM screen WHERE id = ?";
        Object[] params = {id};
        List<Screen> screens = dbHelper.executeQuery(sql, params, Screen.class);
        if (screens.isEmpty()) return null;
        return screens.get(0);
    }

    // Find Screen by Name
    public Screen findByName(String name) {
        String sql = "SELECT * FROM screen WHERE name = ?";
        Object[] params = {name};
        List<Screen> screens = dbHelper.executeQuery(sql, params, Screen.class);
        if (screens.isEmpty()) return null;
        return screens.get(0);
    }

    // Get all screens
    public List<Screen> findAll() {
        String sql = "SELECT * FROM screen";
        Object[] params = {};
        return dbHelper.executeQuery(sql, params, Screen.class);
    }

    // Paginated query for Screens
    public Map<String, Object> findAllWithPagination(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        String sql = "SELECT * FROM screen LIMIT ? OFFSET ?";
        Object[] params = {pageSize, offset};
        List<Screen> screens = dbHelper.executeQuery(sql, params, Screen.class);

        String countSql = "SELECT COUNT(*) FROM screen";
        Object[] countParams = {};
        List<Integer> totalRecordsList = dbHelper.executeQuery(countSql, countParams, Integer.class);
        int totalRecords = totalRecordsList.isEmpty() ? 0 : totalRecordsList.get(0);

        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("screenList", screens);
        result.put("totalRecords", totalRecords);
        result.put("totalPages", totalPages);
        result.put("currentPage", pageNum);

        return result;
    }

    // Clear all Screen data
    public void clearData() {
        dbHelper.clearData("screen");
    }

    // Drop the Screen table
    public void dropTable() {
        dbHelper.dropTable("screen");
    }
}
